var days = getQueryString("days") || 15;

document.title = "t-io官网访问统计，由于IP库不可能时时更新，所以部分IP统计不是太准，IP库使用的是ip2region";


$(function () {

    //百度地图示例：http://lbsyun.baidu.com/index${api_suf}?title=jspopular3.0
    //百度一些API：http://lbsyun.baidu.com/index${api_suf}?title=webapi/ip-api

    // var map = new BMap.Map("baidumap");  
    // map.centerAndZoom(new BMap.Point(116.403884,39.914887), 13);  
    // map.enableScrollWheelZoom();  
    // var marker=new BMap.Marker(new BMap.Point(116.403884,39.914887));  
    // map.addOverlay(marker);  
    // // var licontent="<b>天安门</b><br>";  
    // //     licontent+="<span><strong>地址：</strong>北京市东城区天安门广场北侧</span><br>";  
    // //     licontent+="<span><strong>电话：</strong>(010)63095718,(010)63095630</span><br>";  
    // //     licontent+="<span class=\"input\"><strong></strong><input class=\"outset\" type=\"text\" name=\"origin\" value=\"北京站\"/><input class=\"outset-but\" type=\"button\" value=\"公交\" onclick=\"gotobaidu(1)\" /><input class=\"outset-but\"" type=\"button\" value=\"驾车\"  onclick=\"gotobaidu(2)\"/><a class=\"gotob\"" href=\"url=\"http://api.map.baidu.com/direction?destination=latlng:"+marker.getPosition().lat+","+marker.getPosition().lng+"|name:天安门"+"®ion=北京"+"&output=html\" target=\"_blank\"></a></span>";
  
    // // var hiddeninput="<input type=\"hidden\" value=\""+'北京'+\" name=\"region\" /><input type=\"hidden\" value=\"html\" name=\"output\" /><input type=\"hidden\" value=\"driving\" name=\"mode\" /><input type=\"hidden\" value=\"latlng:"+marker.getPosition().lat+","+marker.getPosition().lng+"|name:天安门"+\" name=\"destination\" />";
  
    // var content1 = "";//"<form id=\"gotobaiduform\" action=\"https://api.map.baidu.com/direction\" target=\"_blank\" method=\"get\">" + licontent +hiddeninput+"</form>";
   
    // var opts1 = { width: 300 };  
        
    // var  infoWindow = new BMap.InfoWindow(content1, opts1);  
    // marker.openInfoWindow(infoWindow);  
    // marker.addEventListener('click',function(){
    //     marker.openInfoWindow(infoWindow);
    // });  
      
    // function gotobaidu(type)  
    // {  
    //     if($.trim($("input[name=origin]").val())=="")  
    //     {  
    //         alert("请输入起点！");  
    //         return;  
    //     }else{  
    //         if(type==1)  
    //         {  
    //             $("input[name=mode]").val("transit");  
    //             $("#gotobaiduform")[0].submit();  
    //         }else if(type==2)  
    //         {      
    //             $("input[name=mode]").val("driving");          
    //             $("#gotobaiduform")[0].submit();  
    //         }  
    //     }  
    // } 



    /**
     * -- 按省统计点击量(地图)
        ---------------------------------------------
        --  hitcount | ipcount      |  province
        --  6565     |   545	    |  浙江省
        --  5443     |   434	    |  湖南省
        ---------------------------------------------
     */
    ajax.get("/stat/statIpAndHitsByProvince", {
        data: {
            // "pageNumber": pageNumber,
            // "pageSize": pageSize
            days: days
        },
        success: function (resp) {
            var list = resp.data;

            // var days = [];
            var ipcounts = [];
            var hitcounts = [];
            for (var i = 0; i < list.length; i++) {
                var item = list[i];
                var p = item.province;
                if (p.endsWith("省")) {
                    p = p.substring(0, p.length - 1);
                }
                if (p.endsWith("市")) {
                    p = p.substring(0, p.length - 1);
                }
                if ("广西壮族自治区" == p) {
                    p = "广西";
                } else if ("新疆维吾尔自治区" == p) {
                    p = "新疆";
                } else if ("内蒙古自治区" == p) {
                    p = "内蒙古";
                } else if ("宁夏回族自治区" == p) {
                    p = "宁夏";
                }


                hitcounts.push({ 'name': p, 'value': item.hitcount });
                ipcounts.push({ 'name': p, 'value': item.ipcount });
            }

            log("hitcounts,", hitcounts);
            log("ipcounts,", ipcounts);

            var dom = document.getElementById("statIpAndHitsByProvince");
            var myChart = echarts.init(dom);
            var app = {};
            var option = null;


            option = {
                title: {
                    text: '按省统计',
                    subtext: '只统计主要页面的已知的国内IP（国外IP和一些库中不存在IP不统计）',
                    left: 'center'
                },
                tooltip: {
                    trigger: 'item'
                },
                legend: {
                    orient: 'vertical',
                    left: 'left',
                    data: ['页面点击量', '独立IP数']
                },
                visualMap: {
                    min: 0,
                    max: 10000,
                    left: 'left',
                    top: 'bottom',
                    text: ['高', '低'],           // 文本，默认为数值文本
                    calculable: true,
                    inRange: {                               //定义 在选中范围中 的视觉元素
                        color: ['#CCCCFF', '#7006e3'],
                        symbolSize: [30, 100]
                    },
                    outOfRange: {  //定义 在选中范围外 的视觉元素。
                        color: ['#CCCCFF', '#7006e3'],
                        symbolSize: [30, 100]
                    },
                },
                toolbox: {
                    show: true,
                    orient: 'vertical',
                    left: 'right',
                    top: 'center',
                    feature: {
                        dataView: { readOnly: false },
                        restore: {},
                        saveAsImage: {}
                    }
                },
                series: [
                    {
                        name: '页面点击量',
                        type: 'map',
                        mapType: 'china',
                        roam: false,
                        label: {
                            normal: {
                                show: true
                            },
                            emphasis: {
                                show: true
                            }
                        },
                        data: hitcounts
                    },
                    {
                        name: '独立IP数',
                        type: 'map',
                        mapType: 'china',
                        label: {
                            normal: {
                                show: true
                            },
                            emphasis: {
                                show: true
                            }
                        },
                        data: ipcounts
                    }
                ]
            };;
            if (option && typeof option === "object") {
                myChart.setOption(option, true);
            }

        }
    });

    /**
        * 显示在柱上的一些信息
        */
    var labelOption = {
        normal: {
            show: true,
            position: 'insideBottom',
            distance: 59,
            align: 'right',
            verticalAlign: 'middle',
            rotate: 58,
            formatter: '{a} {c}',  //'{a}\r\n{c}'
            fontSize: 14,
            rich: {
                name: {
                    textBorderColor: '#fff'
                }
            }
        }
    };

    /**
     *  -- 按天统计独立的ip数
        ---------------------------
        --    d         |  count
        -- 2018-04-16	|  35
        -- 2018-04-17	|  222
        ---------------------------
        */
    ajax.get("/stat/ipCountByDay", {
        data: {
            // "pageNumber": pageNumber,
            // "pageSize": pageSize
            days: days
        },
        success: function (resp) {
            var list = resp.data;

            var days = [];
            var counts = [];
            for (var i = 0; i < list.length; i++) {
                var item = list[i];
                days.push(item.d);
                counts.push(item.count);
            }


            var dom = document.getElementById("ipCountByDay");
            var myChart = echarts.init(dom);
            var app = {};
            var option = null;

            option = {
                title: {
                    text: '独立IP数',
                    subtext: '一个IP不管访问多少次，都只计一次数（本数据并不实时更新，每5分钟同步一次数据）'
                },
                color: ['#3398DB'],
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                        type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                    }
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: [
                    {
                        type: 'category',
                        data: days,
                        axisTick: {
                            alignWithLabel: true
                        }
                    }
                ],
                yAxis: [
                    {
                        type: 'value'
                    }
                ],
                series: [
                    {
                        name: '独立IP数',
                        type: 'bar',
                        barWidth: '60%',
                        data: counts,
                        label: labelOption
                    }
                ]
            };
            ;
            if (option && typeof option === "object") {
                myChart.setOption(option, true);
            }

        }
    });








    var path_name_map = {
        '/index.html': '首页',
        '/doc/index.html': '文档',
        '/case/index.html': '案例',
        '/donation/index.html': '赞赏',
        '/stat/index.html': '监控',
        '/bs/index.html': '商务',
        '/his/index.html': '发展史',
        '/im/index.html': '聊天页',
        '/qa/index.html': '问答',
        '/blog/r/blog-view-onlyhtml.html': "文档切换",
        '/ws-showcase/index.html': 'ws演示页',
        '/blog/r/index.html':'阅读博客'
    };

    /**
     * -- 按天统计页面的访问量
        ---------------------------
        --      path              d       count
        -- /case/index.html	    2018-04-16   24
        -- /case/index.html	    2018-04-17	 109
        -- /blog/index.html	    2018-04-16	 18
        -- /blog/index.html	    2018-04-17	 97
        ---------------------------
    */
    ajax.get("/stat/requestCountByDay", {
        data: {
            // "pageNumber": pageNumber,
            // "pageSize": pageSize
            days: days
        },
        success: function (resp) {
            var list = resp.data;
            var days = [];  //['2014-12-12','2014-12-13']
            var pathnames = [];  //['首页', '文档页']
            var path_counts = {};//{'首页':[45,67,44]}
            var dayPath_count_map = {}; // {'2014-09-09首页': 45}}

            /**
             * {
                    "path":"/case/index.html",
                    "d":"2018-04-16",
                    "count":24
                },
                {
                    "path":"/blog/index.html",
                    "d":"2018-04-16",
                    "count":18
                },
             */
            for (var i = 0; i < list.length; i++) {
                var item = list[i];
                var day = item.d;
                var path = item.path;
                var count = item.count;

                var pathname = path_name_map[path] || path;

                days.push(day);
                pathnames.push(pathname);
                // counts.push(item.count);

                dayPath_count_map[day + pathname] = count;
            }
            days = array_unique(days);
            pathnames = array_unique(pathnames);

            for (var j = 0; j < pathnames.length; j++) {
                var pathname = pathnames[j];
                path_counts[pathname] = [];
                for (var i = 0; i < days.length; i++) {
                    var day = days[i];
                    path_counts[pathname][i] = dayPath_count_map[day + pathname] || 0;
                }
            }

            var xAxis_data = days;
            var series = [];


            for (var i = 0; i < pathnames.length; i++) {
                var pathname = pathnames[i];
                var serie = {
                    name: pathname,  //首页
                    type: 'bar',
                    barGap: 0,
                    data: path_counts[pathname],//[2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3],
                    // label: labelOption,
                    // markPoint: {
                    //     data: [
                    //         { type: 'max', name: '最大值' },
                    //         { type: 'min', name: '最小值' }
                    //     ]
                    // },
                    // markLine: {
                    //     data: [
                    //         { type: 'average', name: '平均值' }
                    //     ]
                    // }
                };

                series[i] = serie;
            }




            log("days:", days);
            log("pathnames:", pathnames);
            log("path_counts:", path_counts);
            log("dayPath_count_map:" + dayPath_count_map);














            var dom = document.getElementById("requestCountByDay");
            var myChart = echarts.init(dom);
            var app = {};
            var option = null;
            option = {
                title: {
                    text: '页面点击量',
                    subtext: '点一次计一次（本数据并不实时更新，每5分钟同步一次数据）'
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                        type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                    }
                },
                legend: {
                    data: pathnames
                },
                toolbox: {
                    show: true,
                    feature: {
                        dataView: { show: true, readOnly: false },
                        magicType: { show: true, type: ['line', 'bar'] },
                        restore: { show: true },
                        saveAsImage: { show: true }
                    }
                },
                calculable: true,
                xAxis: [
                    {
                        type: 'category',
                        data: xAxis_data
                    }
                ],
                yAxis: [
                    {
                        type: 'value'
                    }
                ],
                series: series
            };
            ;
            if (option && typeof option === "object") {
                myChart.setOption(option, true);
            }



        }
    });



    







});

